//
//  FirstViewController.m
//  Server
//
//  Created by 顾悦 on 16/3/21.
//
//

#import "HomeViewController.h"

#import "OrderTableViewCell.h"
#import "CustomTableViewCell.h"
#import "SendTableViewCell.h"
#import "BuyTableViewCell.h"
#import "HelpTableViewCell.h"
#import "LaundryTableViewCell.h"

#import "WaitReceiveViewController.h"
#import "UserInfoController.h"

#import "OrderManagerService.h"
#import "UserWebService.h"
#import "GetService.h"

#import "DOPDropDownMenu.h"
#import "SVPullToRefresh.h"
#import "LoadingView.h"
#import "UIImageView+WebCache.h"

#import "GrabModel.h"

@import CoreLocation;

@interface HomeViewController ()<UITableViewDataSource,UITableViewDelegate,DOPDropDownMenuDataSource,DOPDropDownMenuDelegate, CLLocationManagerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableview;
@property (weak, nonatomic) IBOutlet UIView *noDataView;

@property (weak, nonatomic) IBOutlet UIButton *distanceBtn;
@property (weak, nonatomic) IBOutlet UIButton *timeBtn;
@property (strong, nonatomic) DOPDropDownMenu *menu;

@property (copy, nonatomic) NSString *timeSort;
@property (copy, nonatomic) NSString *distanceSort;
@property (strong, nonatomic) NSDictionary *bizSort;
@property (copy, nonatomic) NSString *selectSortItemCode;
@property (copy, nonatomic) NSString *prefs;
@property (nonatomic) NSUInteger pageIndex;
@property (nonatomic) NSUInteger pageSize;

@property(nonatomic,strong)OrderManagerService * orderManage;

@property(nonatomic,strong)NSMutableArray * dataArray;

@property(nonatomic,strong)NSMutableArray * sortItems;
@property(nonatomic,strong)UIImage * cellImage;

@property(nonatomic,strong)GetService * getservice;
@property(nonatomic,strong)NSString * str;

@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic) NSTimeInterval lastUpdateTime;
@property (nonatomic) CLLocationDegrees latitude;
@property (nonatomic) CLLocationDegrees longitude;
@property (nonatomic) NSInteger uploadGPSFrequency;

@end

@implementation HomeViewController

- (NSString *)distanceSort {
    return self.distanceBtn.selected ? @"2" : @"1";
}

- (NSString *)timeSort {
    return self.timeBtn.selected ? @"2" : @"1";
}

- (NSString *)prefs {
    if (!_prefs) {
        _prefs = @"1";
    }
    return _prefs;
}

- (NSString *)selectSortItemCode {
    if (!_selectSortItemCode) {
        _selectSortItemCode = [_sortItems firstObject][@"CategoryId"];
    }
    
    return _selectSortItemCode;
}

- (NSMutableArray *)sortItems {
    if (!_sortItems) {
        _sortItems = [@[@{@"CategoryId": @"", @"CategoryName": @"全部业务"}] mutableCopy];
    }
    return _sortItems;
}

- (NSUInteger)pageSize {
    if (_pageSize == 0) {
        _pageSize = 100;
    }
    
    return _pageSize;
}

- (DOPDropDownMenu *)menu {
    if (!_menu) {
        
        _menu = [[DOPDropDownMenu alloc] initWithOrigin:CGPointMake([UIScreen mainScreen].bounds.size.width/2+55,self.distanceBtn.frame.size.height/2-10) andHeight:40];
        
        _menu.frame = CGRectMake([UIScreen mainScreen].bounds.size.width/2+55, 2, [UIScreen mainScreen].bounds.size.width/2-70, 42);
        _menu.dataSource = self;
        _menu.delegate = self;
        _menu.textColor = [UIColor lightGrayColor];
    }
    
    return _menu;
}
-(void)BtnSeparatorLine{
    UILabel * lab1 = [[UILabel alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width/3, 13, 1, 20)];
    lab1.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:lab1];
    UILabel * lab2 = [[UILabel alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width/3*2-15, 13, 1, 20)];
    lab2.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:lab2];
}

- (CLLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = CLLocationManager.new;
        _locationManager.delegate = self;
    }
    
    return _locationManager;
}

- (NSInteger)uploadGPSFrequency {
    if (_uploadGPSFrequency <= 0) {
        _uploadGPSFrequency =  3;
    }
    
    return _uploadGPSFrequency;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.menu];
    
    [self BtnSeparatorLine];
    self.dataArray = [NSMutableArray new];
    self.sortItems = [NSMutableArray new];
    
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.separatorStyle=UITableViewCellSeparatorStyleNone;

    
    self.distanceBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 45, 0, -45);
    self.distanceBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 10);
    [self.distanceBtn addTarget:self action:@selector(distanceClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.timeBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 45, 0, -45);
    self.timeBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 10);
    [self.timeBtn addTarget:self action:@selector(timeClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self getServiceCategory];
    
    if ([CLLocationManager locationServicesEnabled]) {
        if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
            [self.locationManager requestWhenInUseAuthorization];
        } else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse) {
            [self.locationManager startUpdatingLocation];
        } else {
            [self requestData];
        }
    } else {
        [self requestData];
    }

    __weak HomeViewController * weakeself = self;
    [self.tableview addPullToRefreshWithActionHandler:^{
        [weakeself toRefresh];
    }];
    
    [self.tableview addInfiniteScrollingWithActionHandler:^{
        [weakeself toBottomRefresh];
    }];

    self.tableview.estimatedRowHeight = 115.0;
    self.tableview.rowHeight = UITableViewAutomaticDimension;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appResumed) name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResign) name:UIApplicationWillResignActiveNotification object:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
}

- (void)appResumed {
    if ([CLLocationManager locationServicesEnabled]) {
        if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse) {
            [self.locationManager startUpdatingLocation];
        }
    }
}

- (void)appWillResign {
    [self.locationManager stopUpdatingLocation];
}

- (void)toRefresh
{
    dispatch_async(dispatch_get_main_queue(), ^{
        //[self.dataArray removeAllObjects];
        [self.tableview.pullToRefreshView startAnimating];

        [self requestData];
    });
    
}
- (void)toBottomRefresh
{
    if (!(self.tableview.pullToRefreshView.state == SVPullToRefreshStateStopped)) {
        return;
    }
   // __weak HomeViewController * weakeself = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableview.pullToRefreshView startAnimating];
        [self requestDataPagingEnabled:YES];
    });
    
}

-(void)distanceClick:(UIButton*)btn{
    btn.selected=!btn.selected;
    self.prefs = @"1";
    [self requestData];
}
-(void)timeClick:(UIButton*)btn{
    btn.selected=!btn.selected;
    self.prefs = @"2";
    [self requestData];
}

- (NSInteger)numberOfColumnsInMenu:(DOPDropDownMenu *)menu {
    
    return 1;
}

- (NSInteger)menu:(DOPDropDownMenu *)menu numberOfRowsInColumn:(NSInteger)column {
    
    return self.sortItems.count;
}

/**
 *  返回 menu 第column列 每行title
 */
- (NSString *)menu:(DOPDropDownMenu *)menu titleForRowAtIndexPath:(DOPIndexPath *)indexPath {
    return self.sortItems[indexPath.row][@"CategoryName"];
}


- (void)menu:(DOPDropDownMenu *)menu didSelectRowAtIndexPath:(DOPIndexPath *)indexPath {
    self.selectSortItemCode = self.sortItems[indexPath.row][@"CategoryId"];
    [self requestData];
}
-(void)getServiceCategory{
    self.orderManage = [OrderManagerService new];
    self.getservice = [GetService new];
    [self.getservice getService:^(NSArray *items, NSError *error) {
        NSMutableArray *bizs = [@[@{@"CategoryId": @"", @"CategoryName": @"全部业务"}] mutableCopy];
        [bizs addObjectsFromArray:items];
        self.sortItems = bizs;
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.menu reloadData];
        });
    }];
}

-(void)requestData{
    [self.tableview.pullToRefreshView startAnimating];
    [self requestDataPagingEnabled:NO];
}

- (void)requestDataPagingEnabled:(BOOL)flag {
    if (!flag) {
        self.pageIndex = 0;
    }
    [self.orderManage getAllOrder:[UserInfoController userID] distance:self.distanceSort dateOrder:self.timeSort distanceAnddate:self.prefs serviceId:self.selectSortItemCode ?: @"" longitude:@(self.longitude) latitude:@(self.latitude) pageNo:@(self.pageIndex + 1) pageSize:@(self.pageSize) completion:^(NSArray *items, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableview.pullToRefreshView stopAnimating];
            [self.tableview.infiniteScrollingView stopAnimating];
        });
        if (error) {
            [LoadingView showToast:[error localizedDescription]];
        } else {
            GrabModel * model = [GrabModel new];
            
            if (flag) {
                [self.dataArray addObjectsFromArray:[model model:items]];
            } else {
                self.dataArray = [model model:items];
            }
            self.pageIndex++;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableview reloadData];
            self.noDataView.hidden = self.dataArray.count;
        });
        
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OrderTableViewCell *cell = OrderTableViewCell.new;
    GrabModel * model = [GrabModel new];
    
    if (self.dataArray.count > indexPath.row) {
        model = self.dataArray[indexPath.row];
    }
    
    NSString *cat1ID = [model.serviceBigid uppercaseString];
    
    if ([cat1ID isEqualToString:GUIDErrand]){
        NSString *cat2ID = [model.serveSmallid uppercaseString];
        if ([cat2ID isEqualToString:GUIDSend]) {
            cell = (SendTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"SendTableViewCell"];
            if (cell == nil) {
                cell = [[[NSBundle mainBundle]loadNibNamed:@"SendTableViewCell" owner:self options:nil]firstObject];
                [cell.GrabBtn addTarget:self action:@selector(grabClick:) forControlEvents:UIControlEventTouchUpInside];
                
            }
        }
        else if ([cat2ID isEqualToString:GUIDBuy]) {
            cell = (BuyTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"BuyTableViewCell"];
            if (cell == nil) {
                cell = [[[NSBundle mainBundle]loadNibNamed:@"BuyTableViewCell" owner:self options:nil]firstObject];
                [cell.GrabBtn addTarget:self action:@selector(grabClick:) forControlEvents:UIControlEventTouchUpInside];
                
            }
        }
        else if ([cat2ID isEqualToString:GUIDHelp]) {
            cell = (HelpTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"HelpTableViewCell"];
            if (cell == nil) {
                cell = [[[NSBundle mainBundle]loadNibNamed:@"HelpTableViewCell" owner:self options:nil]firstObject];
                [cell.GrabBtn addTarget:self action:@selector(grabClick:) forControlEvents:UIControlEventTouchUpInside];
                
            }
        }
        cell.serverImage.image = [UIImage imageNamed:@"跑腿"];
    }
    else if ([cat1ID isEqualToString:GUIDLaundry]) {
        cell = (LaundryTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"LaundryTableViewCell"];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"LaundryTableViewCell" owner:self options:nil]firstObject];
            [cell.GrabBtn addTarget:self action:@selector(grabClick:) forControlEvents:UIControlEventTouchUpInside];
            
        }
        cell.serverImage.image = [UIImage imageNamed:@"洗衣"];
    }
    else {
        cell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"CustomTableViewCell"];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"CustomTableViewCell" owner:self options:nil]firstObject];
            [cell.GrabBtn addTarget:self action:@selector(grabClick:) forControlEvents:UIControlEventTouchUpInside];
            
        }
        
        if ([cat1ID isEqualToString:GUIDRepair]) {
            cell.serverImage.image = [UIImage imageNamed:@"维修"];
        }
        else if ([cat1ID isEqualToString:GUIDCarWash]){
            cell.serverImage.image = [UIImage imageNamed:@"洗车"];
        }
        else if ([cat1ID isEqualToString:GUIDTeach]){
            cell.serverImage.image = [UIImage imageNamed:@"家教"];
        }
        else if ([cat1ID isEqualToString:GUIDHouse]){
            cell.serverImage.image = [UIImage imageNamed:@"家政"];
        }
    }
    
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    
    cell.price.hidden = cell.priceUnitLabel.hidden = [cat1ID isEqualToString:GUIDLaundry];

    cell.serverName.text = model.serveName;
    
    UIColor *orangeColor = [UIColor colorWithRed:255/255.0 green:73/255.0 blue:38/255.0 alpha:1.0];
    if ([model.orderPay isEqualToString:@"1"]) {
        cell.payLB.text = @"已付";
        cell.payLB.textColor = orangeColor;
        cell.payLB.layer.borderColor = orangeColor.CGColor;
    }
    else if ([model.orderPay isEqualToString:@"0"]){
        cell.payLB.text = @"未付";
        cell.payLB.textColor = [UIColor lightGrayColor];
        cell.payLB.layer.borderColor = [UIColor lightGrayColor].CGColor;
    }
    
    cell.firstAddress.text = model.firstaddress;
    cell.secondAddress.text = model.secondaddress;
    cell.remark.text = model.ordermark.length ? model.ordermark : @"无";
    cell.time.text = model.servetime;
    cell.distance.text = model.distance;
    cell.price.text = model.price;
    cell.bonusPriceLabel.hidden = !model.isMarkup;
    cell.bonusPriceLabel.text = [NSString stringWithFormat:@"(含加价:%@元)", model.markupValue];
    cell.recieverAddressLabel.text = model.receiverAddress;
    cell.helperToFromDistanceLabel.text = [NSString stringWithFormat:@"%@公里", model.helperToFromDistance];
    cell.helperToRecieveDistanceLabel.text = [NSString stringWithFormat:@"%@公里", model.helperToRecieveDistance];
    cell.goodsDescriptionLabel.text = model.goodsDescription;
    cell.helpDescriptionLabel.text = model.helpDescription;
    cell.totalNumberLabel.text = [NSString stringWithFormat:@"%@件", model.totalNumber];
    
    cell.GrabBtn.tag = indexPath.row;

    
    return cell;
}
-(void)grabClick:(UIButton*)btn{
    GrabModel * model = [GrabModel new];
    
    model = self.dataArray[btn.tag];
    [LoadingView show];
    [self.orderManage grabOrder:[UserInfoController userID] OrderId:model.orderid HelperAreaId:@"" completionHanlder:^(NSArray *items, NSError *error) {
        [LoadingView dismiss];
        if (!error) {
            [LoadingView showToast:@"抢单成功"];
            [self.dataArray removeAllObjects];
            [self toRefresh];

        }
        else if ((long)error.code == -8){
            [LoadingView showToast:@"该订单已被抢"];
        }
    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 15;
}

//-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return 150;
//}

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *newLocation = locations.firstObject;
    NSDate *eventDate = newLocation.timestamp;
    NSTimeInterval howRecent = [eventDate timeIntervalSince1970];
    if (self.lastUpdateTime == 0) {
        self.latitude = newLocation.coordinate.latitude;
        self.longitude = newLocation.coordinate.longitude;
        self.lastUpdateTime = howRecent;
        [self requestData];
        [UserWebService.new fetchSaveGPSFrequencyCompletionHanlder:^(NSArray *items, NSError *error) {
            NSDictionary *f = items.firstObject;
            self.uploadGPSFrequency = [f[@"ExtData"] integerValue];
        }];
    } else {
        if ((howRecent - self.lastUpdateTime) > self.uploadGPSFrequency * 60) {
            self.latitude = newLocation.coordinate.latitude;
            self.longitude = newLocation.coordinate.longitude;
            self.lastUpdateTime = howRecent;
            [UserWebService.new saveHelperGPSWithLatitude:@(self.latitude) longitude:@(self.longitude) completionHanlder:^(NSArray *items, NSError *error) {
                
            }];
        }
    }
    
//    [self.locationManager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error {
    if (self.lastUpdateTime == 0) {
        [self requestData];
    }
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse) {
        [self.locationManager startUpdatingLocation];
    } else if (status == kCLAuthorizationStatusDenied) {
        [self requestData];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
